<template>
  <div class="app-container">
    <el-card shadow="never" v-loading="loading">
      <el-row :gutter="5">
        <el-col :span="24" class="main-card-view">
          <el-row v-if="userInfo.roleName === '运营人员' || userInfo.roleName === '管理员'">
            <el-card shadow="never" class="top-search-view-card" >
              <el-row>
                <el-form :inline="true" :model="searchForm" class="demo-form-inline search-view">
                  <el-form-item label="机构名称">
                    <el-input v-model="searchForm.organName" placeholder="请输入机构名称"></el-input>
                  </el-form-item>
                  <el-form-item label="等级">
                    <el-select style="width: 100%;" v-model="searchForm.grade" clearable>
                      <el-option v-for="(item) in gradeList" :key="item.uid" :label="item.name" :value="item.name" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="区域">
                    <el-cascader v-model="searchForm.area" :options="regionOptions" placeholder="请选择地区"
                      @change="closeTanc" :props="searchProps"></el-cascader>
                  </el-form-item>
                  <el-form-item label="属地">
                    <el-select style="width: 100%;" v-model="searchForm.dependency">
                      <el-option v-for="(item, index) in ['省级', '市级', '区县级']" :key="index" :label="item" :value="item" />
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleSearch" class="search-button">查询</el-button>
                    <el-button type="primary" @click="showCreateDialog" class="new-button">添加</el-button>
                  </el-form-item>
                </el-form>
              </el-row>
            </el-card>
          </el-row>

          <el-row>
            <el-card shadow="never">
              <el-table :data="tableData" :stripe="true" style="width: 100%">

                <el-table-column prop="classification" align="center" label="机构分类" />
                <el-table-column prop="organName" align="center" label="机构名称" />
                <el-table-column prop="grade" align="center" label="级别" />
                <el-table-column prop="phone" align="center" label="电话" />
                <el-table-column prop="area" align="center" label="区域">
                </el-table-column>
                <el-table-column prop="expertNum" align="center" label="专家数" />
                 <el-table-column prop="dependency" align="center" label="等级" />
                <el-table-column align="center" label="操作" width="200">
                  <template slot-scope="scope">
                    <!--                                        <el-button type="text" class="table-details-btn"-->
                    <!--                                                   @click="handleDetails(scope.$index, scope.row)"></el-button>&lt;!&ndash;详情&ndash;&gt;-->
                    <el-button type="text" class="table-edit-btn"
                      @click="showEditDialog(scope.$index, scope.row)"></el-button><!--编辑-->
                    <el-button type="text" @click="showPwsDialog(scope.$index, scope.row)">修改密码</el-button><!--编辑-->
                   <!-- <el-button type="text" class="table-delete-btn"
                      @click="handleDelete(scope.$index, scope.row)"></el-button> --><!--删除-->
                  </template>
                </el-table-column>
              </el-table>
              <XPagination ref="pageInfo" :total="total" :get-data="getList" />
            </el-card>
          </el-row>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog width="80%" :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form label-width="150px" ref="form" :model="form" :rules="formRules">
        <el-tabs>
          <el-tab-pane label="机构基本信息" />
        </el-tabs>
        <div style="display: flex;flex-wrap: wrap;">
          <el-form-item label="机构名称" prop="organName" style="width: 49%;">
            <el-input v-model="form.organName" />
          </el-form-item>
          <el-form-item label="级别" prop="grade" style="width: 49%;">
            <el-select style="width: 100%;" v-model="form.grade" clearable>
              <el-option v-for="(item) in gradeList" :key="item.uid" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="电话" prop="phone" style="width: 49%;">
            <el-input v-model="form.phone" />
          </el-form-item>
          <el-form-item label="分类" prop="classification" style="width: 49%;">
            <el-select style="width: 100%;" v-model="form.classification">
              <el-option v-for="(item, index) in sortList" :key="index" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="区域" prop="area" style="width: 49%;">
            <el-cascader ref="regionSelect" v-model="regionSelect" :options="regionOptions" placeholder="请选择地区"
              @change="handleRegionChange" :props="treeProps"></el-cascader>
          </el-form-item>
          <el-form-item label="等级" prop="dependency" style="width: 49%;">
            <el-select style="width: 100%;" v-model="form.dependency">
              <el-option v-for="(item, index) in ['省级', '市级', '区县级']" :key="index" :label="item" :value="item" />
            </el-select>
          </el-form-item>
        </div>
        <el-row>
          <el-form-item label="诊疗科目" prop="subject">
            <el-input v-model="form.subject" type="textarea" :autosize="{ minRows: 4, maxRows: 10 }" />
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="form.address" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="医院简介" prop="businessScope">
            <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" v-model="form.businessScope" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="填报人" prop="contacts">
              <el-input v-model="form.contacts" />
            </el-form-item>
            <el-form-item label="填报人电话" prop="contactsPhone">
              <el-input v-model="form.contactsPhone" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>


    <el-dialog width="50%" :title="dialogPwsTitle" :visible.sync="dialogPwsVisible">
      <el-form label-width="150px" ref="form" :model="form" :rules="formRules">
        <el-tabs>
          <el-tab-pane label="机构账户信息" />
        </el-tabs>
        <el-row style="padding-top: 20px;">
          <el-col :span="20">
            <el-form-item label="登录账户" prop="account">
              <el-input v-model="form.account" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password"/>
            </el-form-item>
            <el-form-item label="确认密码" prop="password">
              <el-input v-model="form.verifyPwd" type="password"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="passwordSave">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import XPagination from "../../components/xpagination/XPagination";
import { Cascader } from 'element-ui';
import * as dictionaryInfo from "../../api/dictionaryInfo"
import * as organInfo from "../../api/organInfo"
import * as areaInfo from "../../api/areaInfo"
import * as formUtils from "../../utils/formUtils"
import XUpload from "../../components/xupload/XUpload";
export default {
  name: "list",
  components: { XUpload, XPagination, 'el-cascader': Cascader, },
  data () {
    return {
      searchForm: {
        creditIdentifier: "",
        grade: "",
        organName: "",
      },
      tableData: [],
      loading: false,
      dialogVisible: false,
      dialogPwsVisible: false,
      userInfo: {},
      total: 0,
      dialogTitle: "添加机构信息",
      form: {
        uid: "",
        organName: "",
        creditIdentifier: "",
        grade: "",
        unitName: "",
        unitUid: "",
        phone: "",
        legalPeo: "",
        legalPhone: "",
        classification: "",

        province: "",
        city: "",
        area: "",
        registerCapital: "",
        businessNature: "",
        subject: "",
        address: "",
        floorSpace: "",
        coverArea: "",
        bed: "",
        postalCode: "",
        introduction: "",
        startPeriodOfValidity: "",
        endPeriodOfValidity: "",
        periodOfValidity: "否",
        businessScope: "",
        contacts: "",
        status: "0",
        contactsPhone: "",
        account: "",
        password: "",
        verifyPwd:"",
        timeRange: []
      },
      editStatus: "add",
      formRules: {
        organName: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        creditIdentifier: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        grade: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        unitName: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '不能为空', trigger: 'blur' },
          {
                  type: 'string',
                  message: '请输入不包含空格的字符',
                  trigger: 'blur',
                  transform(value) {
                    if (value && value.indexOf(' ') === -1) {
                      return value
                    } else {
                      return false
                    }
                  }
                },
                {
                  trigger: 'blur',
                  message: '密码必须由数字、字母、特殊字符组合,请输入6-16位',
                  validator: (rule, value, callback) => {
                    var passwordreg = /(?=.*\d)(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{6,16}/
                    if (!passwordreg.test(value)) {
                      callback(new Error('密码必须由数字、字母、特殊字符组合,请输入6-16位'))
                    }else{
                      callback()
                    }
                  }
                }
        ],
        verifyPwd: [
          { required: true, message: '不能为空', trigger: 'blur' },
          {
                  type: 'string',
                  message: '请输入不包含空格的字符',
                  trigger: 'blur',
                  transform(value) {
                    if (value && value.indexOf(' ') === -1) {
                      return value
                    } else {
                      return false
                    }
                  }
                },
                {
                  trigger: 'blur',
                  message: '密码必须由数字、字母、特殊字符组合,请输入6-16位',
                  validator: (rule, value, callback) => {
                    var passwordreg = /(?=.*\d)(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{6,16}/
                    if (!passwordreg.test(value)) {
                      callback(new Error('密码必须由数字、字母、特殊字符组合,请输入6-16位'))
                    }else{
                      callback()
                    }
                  }
                }
        ],
      },
      gradeList: [],
      unitList: ["事业单位营业"],
      businessNatureList: [],
      sortList: ["医院", "公共卫生","高校", "其他"],
      regionSelect: [],
      regionOptions: [],
      treeProps: {
        children: "childs",
        label: "areaName",
        checkStrictly: true,
        value: "areaName"
      },
      searchProps: {
        children: "childs",
        label: "areaName",
        checkStrictly: true,
        value: "areaName",
        emitPath: false
      },
      dialogPwsTitle: '修改密码',
      verifyPassword: ''
    }
  },
  methods: {
    getList (pageInfo) {
      const param = {
        ...this.searchForm,
        ...pageInfo
      }
      let userInfo = JSON.parse(localStorage.getItem("user_info"))
      if('机构'==userInfo.roleName){
          param.uid=userInfo.uid
      }
      organInfo.queryByPage(param).then(response => {
        console.log(response)
        this.tableData = response.data.data.rows
        this.total = response.data.data.total
        this.loading = false
      }).catch(error => {
        console.log(error)
      })
    },
    handleDelete (index, data) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = {
          uid: data.uid,
        }
        this.loading = true
        organInfo.deleteById(param).then(result => {
          this.loading = false
          this.$message.success(result.data.msg)
          this.handleSearch()
        }).catch(error => {
          this.loading = false
          console.log(error)
        })
      }).catch(() => {
        console.log('取消删除')
      });
    },
    handleSearch () {
      this.$refs.pageInfo.loadData()
    },
    showCreateDialog () {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.regionSelect = [];
        this.dialogTitle = "添加机构信息"
        this.editStatus = "add"
        this.$refs.form.resetFields()
        this.form = Object.assign({}, this.$options.data().form)
        this.verifyPassword = ''
      })
    },
    handleSave () {
      if (this.editStatus === "add") {
        this.handleAdd()
      } else {
        this.handleEdit()
      }
    },
    handleAdd () {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false
        }
        this.form.periodOfValidity = this.setPeriodOfValidity()
        const param = Object.assign({}, this.form)
        formUtils.filterFormFields(param)
        organInfo.insert(param).then(result => {
          this.$message.success(result.data.msg)
          this.dialogVisible = false
          this.handleSearch()
        }).catch(error => {
          this.$message.error(error)
          console.log(error)
        })

      })
    },
    handleEdit () {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false
        }
        this.form.periodOfValidity = this.setPeriodOfValidity()
        const param = Object.assign({}, this.form)
        formUtils.filterFormFields(param)
        organInfo.update(param).then(result => {
          this.$message.success(result.data.msg)
          this.dialogVisible = false
          this.dialogPwsVisible = false
          this.handleSearch()
        }).catch(error => {
          this.$message.error(error)
          console.log(error)
        })
      })
    },
    showEditDialog (index, data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        if (data.area) {
          this.regionSelect = data.area.split('/')
        }
        this.$refs.form.resetFields()
        this.form = Object.assign({}, data)
        this.form.timeRange = [data.startPeriodOfValidity, data.endPeriodOfValidity]
        this.form.periodOfValidity = this.getPeriodOfValidity(data.periodOfValidity)
        this.dialogTitle = "编辑机构信息"
        this.editStatus = "edit"
        this.verifyPassword = ''
      })
    },

    showPwsDialog (index, data) {
      this.dialogPwsVisible = true
      this.$nextTick(() => {
        this.form = {
          uid: data.uid,
          account: data.account,
        }
        this.dialogTitle = "编辑账户信息"
        this.editStatus = "edit"
      })
    },
    getParams () {
      if (this.form.timeRange && this.form.timeRange.length > 0) {
        this.form.startPeriodOfValidity = this.form.timeRange[0];
        this.form.endPeriodOfValidity = this.form.timeRange[1];
      }
      return Object.assign({}, this.form, {
        timeRange: undefined
      })
    },
    setPeriodOfValidity () {
      if (this.form.periodOfValidity) {
        return "是"
      } else {
        return "否"
      }
    },
    getPeriodOfValidity (data) {
      if (data === "是") {
        return true
      } else {
        return false
      }
    },
    closeTanc (e) {
      this.$refs.cascader.dropDownVisible = false
    },
    handleRegionChange (value) {
      this.$refs.regionSelect.dropDownVisible = false
      this.form.area = value.join('/');
    },
    getGradeList () {
      dictionaryInfo.queryDictionary({
        lastDict: "jigou-03"
      }).then(response => {
        this.gradeList = response.data.data.rows
        this.gradeList.sort((a, b) => {
          return a.sort - b.sort
        })
      }).catch(error => {
        console.log(error)
      })
      dictionaryInfo.queryDictionary({
        lastDict: "jigou-02"
      }).then(response => {
        this.businessNatureList = response.data.data.rows
        this.gradeList.sort((a, b) => {
          return a.sort - b.sort
        })
      }).catch(error => {
        console.log(error)
      })
    },
    getData () {
      areaInfo.queryTree({}).then(result => {
        this.regionOptions = result.data.data;
        this.regionOptions = this.buildTree(this.regionOptions)
      }).catch(error => {
        console.log(error);
      })
    },
    buildTree (tree) {
      tree.forEach(item => {
        if (item.childs && item.childs.length > 0) {
          item.childs = this.buildTree(item.childs);
        } else if (item.childs && item.childs.length === 0) {
          delete item.childs;
        }
      });
      return tree;
    },
    passwordSave () {
      if (this.form.verifyPwd === this.form.password) {
        this.handleEdit()
      } else {
        this.$message.error('两次密码不同！！！')
      }
    }
  },
  mounted () {
    this.userInfo = JSON.parse(localStorage.getItem('user_info'))
    this.handleSearch()
    this.getGradeList()
    this.getData()
  }
}
</script>

<style scoped lang="scss"></style>
